﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

namespace EF
{
    public class EFInspectUniquePerm
    {
        #region constant variables
        public const string Result_ListTitle = @"EFInspectUniquePerm";
        public const string Result_ListDescription = @"Inspecting result of sub sites, lists, sub folders and items which have unique permissions";
        public const string History_ListTitle = @"EFInspectUniquePermHistory";
        public const string History_ListDescription = @"History of Inspecting Unique permissions";

        public const string Column_Result_ObjectType = @"ObjectType";
        public const string Column_Result_ModifiedByUser = @"ModifiedByUser";
        public const string Column_Result_ModifiedTime = @"ModifiedTime";
        public const string Column_Result_WebUrl = @"WebUrl";
        public const string Column_Result_ParentUrl = @"ParentUrl";
        public const string Column_Result_Link = @"Link";
        public const string Column_Result_UserRights = @"UserRights";
        public const string Column_Result_ScanTime = @"ScanTime";

        //  EFInspectUniquePermHistory
        public const string Column_History_WebCount = @"WebCount";
        public const string Column_History_ListCount = @"ListCount";
        public const string Column_History_LibraryCount = @"LibraryCount";
        public const string Column_History_FolderCount = @"FolderCount";
        public const string Column_History_ItemCount = @"ItemCount";
        public const string Column_History_FileCount = @"FileCount";
        public const string Column_History_ActionType = @"ActionType";

        //EFInspectUniquePerm Admin Link
        public const string Column_EFInspectUniquePermJob_AdminLink = @"AdminLink";

        public const string View_Portal = @"Portal";

        //public const string ObjectType_Web = @"Web";
        //public const string ObjectType_List = @"List";
        //public const string ObjectType_Folder = @"Folder";
        //public const string ObjectType_Item = @"Item";

        public enum ObjectType
        {
            Web,
            List,
            Library,
            Folder,
            Item,
            File
        }

        public enum ActionType
        {
            Search,
            Recover
        }

        public const string View_Web = @"vwWeb";
        public const string View_List = @"vwList";
        public const string View_Library = @"vwLibrary";
        public const string View_Folder = @"vwFolder";
        public const string View_Item = @"vwItem";
        public const string View_File = @"vwFile";

        public const string DocLib_SitePages_Title = @"Site Pages";
        public const string DocLib_SitePages_PathName = @"SitePages";
        public const string AdminPage_Name = @"EFInspectUniquePerm";
        public const string AdminPage_Title = "EF Inspect Unique Permissions";
        public const string AdminPage_Url = "SitePages/EFInspectUniquePerm.aspx";

        public const string Zone_TitleBar = @"TitleBar";
        public const string Zone_Header = @"Header";
        public const string Zone_LeftColumn = @"LeftColumn";
        public const string Zone_MiddleColumn = @"MiddleColumn";
        public const string Zone_RightColumn = @"RightColumn";
        public const string Zone_Footer = @"Footer";

        public enum ListViewWebPartToolbarType
        {
            Standard = 0,       //Standard
            FreeForm = 1,       //Freeform
            None = 2,           //None
            ShowToolbar = 4     //ShowToolbar
        }

        public static int _iWebCount = 0;
        public static int _iListCount = 0;
        public static int _iLibraryCount = 0;
        public static int _iFolderCount = 0;
        public static int _iItemCount = 0;
        public static int _iFileCount = 0;

        #endregion

        #region constructor
        public EFInspectUniquePerm()
            : base()
        {

        }
        #endregion

        #region common functions

        public static void logInfo(SPWeb objSPWeb, string strTarget, int iWebCount, int iListCount, int iLibraryCount, int iFolderCount, int iItemCount, int iFileCount, bool boolRecover)
        {
            if (string.IsNullOrEmpty(strTarget))
                return;

            EF.EFInspectUniquePerm.ActionType objActionType = EFInspectUniquePerm.ActionType.Search;
            if (boolRecover)
            {
                objActionType = ActionType.Recover;
            }

            if (strTarget.Length > 230)
                strTarget = strTarget.Substring(0, 230);

            SPList splistHistory = null;
            try
            {
                if (objSPWeb != null)
                {
                    using (SPSite objSPSite = new SPSite(objSPWeb.Site.ID))
                    {
                        using (SPWeb objSPWebRoot = objSPSite.RootWeb)
                        {
                            objSPWebRoot.AllowUnsafeUpdates = true;
                            splistHistory = objSPWebRoot.Lists.TryGetList(History_ListTitle);
                            if (splistHistory != null)
                            {
                                SPListItem itemHistory = splistHistory.AddItem();
                                itemHistory[SPBuiltInFieldId.Title] = strTarget;
                                itemHistory[Column_History_WebCount] = iWebCount;
                                itemHistory[Column_History_ListCount] = iListCount;
                                itemHistory[Column_History_LibraryCount] = iLibraryCount;
                                itemHistory[Column_History_FolderCount] = iFolderCount;
                                itemHistory[Column_History_ItemCount] = iItemCount;
                                itemHistory[Column_History_FileCount] = iFileCount;
                                itemHistory[Column_History_ActionType] = objActionType.ToString();
                                itemHistory.Update();
                            }
                            objSPWebRoot.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logTraceInfo(string.Format(@"ex, strTarget={0}", strTarget));
                logTraceInfo(string.Format(@"ex.Message={0}", ex.Message));
                logTraceInfo(string.Format(@"ex.StackTrace={0}", ex.StackTrace));

                throw;
            }
        }

        public static SPUser GetSPUser(SPWeb objSPWeb, string strUserLoginName)
        {
            SPUser objSPUser = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    objSPUser = objSPWeb.Site.RootWeb.EnsureUser(strUserLoginName);
                });
            }
            catch (Exception ex)
            {
                logTraceInfo(string.Format(@"GetSPUser(), Web.Url={0}, UserLoginName={1}", objSPWeb.Url, strUserLoginName));
                logTraceInfo(string.Format(@"GetSPUser(), ex.Message={0}", ex.Message));
                logTraceInfo(string.Format(@"GetSPUser(), ex.StackTrace={0}", ex.StackTrace));
            }

            return objSPUser;
        }

        //public static SPUser GetSPUserFromPersonField(SPListItem listItem, Guid fieldId)
        //{
        //    SPFieldUser personField = (SPFieldUser)listItem.ParentList.Fields[fieldId];
        //    SPFieldUserValue fieldValue = (SPFieldUserValue)personField.GetFieldValue(listItem[fieldId].ToString());
        //    SPUser objSPUser = fieldValue.User;
        //    return objSPUser;

        //    //SPFieldUser personField = (SPFieldUser)listItem.Fields[fieldId];
        //    //return ((SPFieldUserValue)personField.GetFieldValue(listItem[fieldId].ToString())).User;
        //}

        public static string getPermissionsInfo(SPRoleAssignmentCollection objSPRoleAssignmentCollection)
        {
            string strRightsAll = string.Empty;
            string strRights = string.Empty;
            string strRoleDefinitionBindings = string.Empty;
            string strRoleDefinition = string.Empty;
            foreach (SPRoleAssignment objSPRoleAssignment in objSPRoleAssignmentCollection)
            {
                strRoleDefinitionBindings = string.Empty;
                foreach (SPRoleDefinition objSPRoleDefinition in objSPRoleAssignment.RoleDefinitionBindings)
                {
                    strRoleDefinition = string.Format(@"{0}", objSPRoleDefinition.Name);
                    strRoleDefinitionBindings += strRoleDefinition + @";";
                }
                strRights = string.Format("{0} - {1}", objSPRoleAssignment.Member.Name, strRoleDefinitionBindings);
                //strRightsAll += strRights + @"<br />";
                strRightsAll += strRights + Environment.NewLine;
            }

            return strRightsAll;
        }

        public static void logObject(SPWeb objSPWeb)
        {
            string strParentUrl = string.Empty;
            string strTitle = objSPWeb.Title;
            SPUser objSPUser = null;
            DateTime dtModified = DateTime.MinValue;
            string strUserRights = getPermissionsInfo(objSPWeb.RoleAssignments);
            string strObjectLink = string.Empty;
            strObjectLink = string.Format("{0}, {1}", objSPWeb.ServerRelativeUrl, ObjectType.Web.ToString());
            string strPermissionLink = string.Empty;
            strParentUrl = objSPWeb.ParentWeb.PortalUrl;

            _iWebCount++;

            logObject(objSPWeb, ObjectType.Web, strParentUrl, strTitle, objSPUser, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static void logObject(SPWeb objSPWeb, SPList objSPList)
        {
            //ObjectType objType = ObjectType.List;
            string strParentUrl = string.Empty;
            string strTitle = objSPList.Title;
            SPUser objSPUser = null;
            DateTime dtModified = DateTime.MinValue;
            string strUserRights = getPermissionsInfo(objSPList.RoleAssignments);
            string strObjectLink = string.Empty;
            //if (objSPList.BaseType == SPBaseType.DocumentLibrary)
            //{
            //    objType = ObjectType.Library;
            //    _iLibraryCount++;
            //}
            //else
            //{
            _iListCount++;
            //}

            strObjectLink = string.Format(@"{0}/{1}, {2}", objSPWeb.Url, SPEncode.UrlEncode(objSPList.RootFolder.Url), ObjectType.List.ToString());
            string strPermissionLink = string.Empty;
            strParentUrl = objSPList.ParentWeb.PortalUrl;

            logObject(objSPWeb, ObjectType.List, strParentUrl, strTitle, objSPUser, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static void logObject(SPWeb objSPWeb, SPDocumentLibrary objSPDocumentLibrary)
        {
            string strParentUrl = string.Empty;
            string strTitle = objSPDocumentLibrary.Title;
            SPUser objSPUser = null;
            DateTime dtModified = objSPDocumentLibrary.LastItemModifiedDate;
            string strUserRights = getPermissionsInfo(objSPDocumentLibrary.RoleAssignments);
            string strObjectLink = string.Empty;

            _iLibraryCount++;
            strObjectLink = string.Format(@"{0}/{1}, {2}", objSPWeb.Url, SPEncode.UrlEncode(objSPDocumentLibrary.RootFolder.Url), ObjectType.Library.ToString());
            string strPermissionLink = string.Empty;
            strParentUrl = objSPDocumentLibrary.ParentWeb.PortalUrl;

            logObject(objSPWeb, ObjectType.Library, strParentUrl, strTitle, objSPUser, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static void logObject(SPWeb objSPWeb, SPFolder objSPFolder)
        {
            string strParentUrl = string.Empty;
            string strTitle = objSPFolder.Name;
            SPListItem objSPListItem = objSPFolder.Item;

            SPFieldUser SPFieldUserEditor = (SPFieldUser)objSPListItem.Fields[SPBuiltInFieldId.Editor];
            SPFieldUserValue SPFieldUserValueEditor = (SPFieldUserValue)SPFieldUserEditor.GetFieldValue(objSPListItem[SPBuiltInFieldId.Editor].ToString());
            SPUser objSPUser = SPFieldUserValueEditor.User;
            //SPUser objSPUser = GetSPUser(objSPWeb, Convert.ToString(objSPListItem[SPBuiltInFieldId.Modified_x0020_By]));
            DateTime dtModified = Convert.ToDateTime(objSPListItem[SPBuiltInFieldId.Modified]);
            string strUserRights = getPermissionsInfo(objSPListItem.RoleAssignments);
            string strObjectLink = string.Empty;
            strObjectLink = string.Format(@"{0}/{1}, {2}", objSPWeb.Url, SPEncode.UrlEncode(objSPFolder.Url), ObjectType.Folder.ToString());
            string strPermissionLink = string.Empty;
            strParentUrl = objSPFolder.ParentFolder.Url;

            _iFolderCount++;

            logObject(objSPWeb, ObjectType.Folder, strParentUrl, strTitle, objSPUser, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static void logObject(SPWeb objSPWeb, SPListItem objSPListItem)
        {
            //ObjectType objType = ObjectType.Item;
            string strObjectLink = string.Empty;
            string strParentUrl = string.Empty;
            string strTitle = string.Empty;
            SPUser objSPUser = null;

            //if (objSPListItem.File == null)
            //{
            SPFieldUser SPFieldUserEditor = (SPFieldUser)objSPListItem.Fields[SPBuiltInFieldId.Editor];
            SPFieldUserValue SPFieldUserValueEditor = (SPFieldUserValue)SPFieldUserEditor.GetFieldValue(objSPListItem[SPBuiltInFieldId.Editor].ToString());
            objSPUser = SPFieldUserValueEditor.User;
            strParentUrl = getParentUrl(objSPListItem);
            //  http://sharepoint/Lists/Test/DispForm.aspx?ID=10
            strObjectLink = string.Format(@"{0}/{1}/DispForm.aspx?ID={2}, {3}",
                objSPWeb.Url,
                objSPListItem.ParentList.RootFolder.Url,
                objSPListItem.ID,
                ObjectType.Item.ToString());
            _iItemCount++;
            //}
            //else
            //{
            //    objType = ObjectType.File;
            //    objSPUser = GetSPUser(objSPWeb, Convert.ToString(objSPListItem[SPBuiltInFieldId.Modified_x0020_By]));
            //    strParentUrl = objSPListItem.File.ParentFolder.Url;
            //    strObjectLink = string.Format(@"{0}/{1}, {2}", objSPWeb.Url, objSPListItem.File.Url, objType.ToString());
            //    _iFileCount++;
            //}
            DateTime dtModified = Convert.ToDateTime(objSPListItem[SPBuiltInFieldId.Modified]);
            string strUserRights = getPermissionsInfo(objSPListItem.RoleAssignments);
            //if (objSPListItem.File != null)
            //{
            //    strTitle = objSPListItem.File.Name;
            //}
            //else 
            if (string.IsNullOrEmpty(objSPListItem.Title))
                strTitle = objSPListItem.ID.ToString();
            else
                strTitle = objSPListItem.Title;
            string strPermissionLink = string.Empty;

            logObject(objSPWeb, ObjectType.Item, strParentUrl, strTitle, objSPUser, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static void logObject(SPWeb objSPWeb, SPFile objSPFile)
        {
            string strObjectLink = string.Empty;
            string strParentUrl = string.Empty;
            string strTitle = string.Empty;
            SPListItem objSPListItem = objSPFile.Item;

            strParentUrl = objSPFile.ParentFolder.Url;
            //  http://sharepoint/Play%20Area/Forms/DispForm.aspx?ID=1762
            strObjectLink = string.Format(@"{0}/{1}/Forms/DispForm.aspx?ID={2}, {3}",
                objSPWeb.Url,
                objSPListItem.ParentList.RootFolder.Url,
                objSPListItem.ID,
                ObjectType.File.ToString());
            _iFileCount++;

            DateTime dtModified = objSPFile.TimeLastModified;
            string strUserRights = getPermissionsInfo(objSPListItem.RoleAssignments);
            strTitle = objSPFile.Name;
            string strPermissionLink = string.Empty;

            logObject(objSPWeb, ObjectType.File, strParentUrl, strTitle, objSPFile.ModifiedBy, dtModified, strUserRights, strObjectLink, strPermissionLink);
        }

        public static string getParentUrl(SPListItem objSPListItem)
        {
            try
            {
                string dirPath = SPUtility.GetUrlDirectory(objSPListItem.Url);
                if (dirPath != null)
                {
                    string[] dirs = dirPath.Split(new char[] { '/' });
                    if (dirs.Length > 0)
                    {
                        return (dirs[dirs.Length - 1]);
                    }
                }
            }
            catch (Exception ex)
            {
                logTraceInfo(string.Format(@"getParentUrl(), ex.Message={0}", ex.Message));
                logTraceInfo(string.Format(@"getParentUrl(), ex.StackTrace={0}", ex.StackTrace));

                throw;
            }

            return string.Empty;
        }

        public static void logObject(SPWeb objSPWeb, ObjectType objType, string strParentUrl, string strTitle, SPUser objSPUser, DateTime dtModified, string strUserRights, string strObjectLink, string strPermissionLink)
        {
            SPList splistResult = null;
            if (objSPWeb == null)
            {
                logTraceInfo(string.Format(@"logObject(), objSPWeb is null!"));

                throw new ApplicationException("logObject(), objSPWeb is null!");
            }

            try
            {
                using (SPSite objSPSite = new SPSite(objSPWeb.Site.ID))
                {
                    using (SPWeb objSPWebRoot = objSPSite.RootWeb)
                    {
                        objSPWebRoot.AllowUnsafeUpdates = true;
                        splistResult = objSPWebRoot.Lists.TryGetList(Result_ListTitle);
                        if (splistResult != null)
                        {
                            SPListItem itemResult = splistResult.AddItem();
                            itemResult[SPBuiltInFieldId.Title] = strTitle;
                            itemResult[Column_Result_ObjectType] = objType.ToString();
                            itemResult[Column_Result_WebUrl] = objSPWeb.ServerRelativeUrl;
                            itemResult[Column_Result_ParentUrl] = strParentUrl;
                            itemResult[Column_Result_Link] = strObjectLink;
                            if (dtModified != DateTime.MinValue)
                            {
                                itemResult[Column_Result_ModifiedTime] = dtModified;
                            }
                            if (objSPUser != null)
                            {
                                itemResult[Column_Result_ModifiedByUser] = objSPUser;
                            }
                            itemResult[Column_Result_UserRights] = strUserRights;
                            itemResult[Column_Result_ScanTime] = DateTime.Now;

                            itemResult.Update();
                        }
                        objSPWebRoot.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                logTraceInfo(string.Format(@"logObject(), ex.Message={0}", ex.Message));
                logTraceInfo(string.Format(@"logObject(), ex.StackTrace={0}", ex.StackTrace));
            }
        }

        public static void logTraceInfo(string strMessage)
        {
            if (string.IsNullOrEmpty(strMessage))
                return;

            SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
            diagSvc.WriteTrace(0,
                new SPDiagnosticsCategory("EFInspectUniquePerm", TraceSeverity.Monitorable, EventSeverity.Error),
                TraceSeverity.Monitorable,
                "{0}",
                new object[] { strMessage });
        }

        public static string getServerRelativeUrl(SPWeb objSPWeb, string strWebRelativeUrl)
        {
            string strServerRelativeUrl = string.Empty;
            string strWebServerRelativeUrl = objSPWeb.ServerRelativeUrl;
            if (strWebServerRelativeUrl == @"/") strWebServerRelativeUrl = string.Empty;

            strServerRelativeUrl = strWebServerRelativeUrl + strWebRelativeUrl;
            return strServerRelativeUrl;
        }

        public static string replaceTags(SPListItem itemTarget, string strContent)
        {
            return replaceTags(itemTarget, strContent, false);
        }

        public static string replaceTags(SPListItem itemTarget, string strContent, bool boolUserEmail)
        {
            string strReturn = strContent;
            string strTag = string.Empty;
            string strValue = string.Empty;
            int iCfgItemId = itemTarget.ID;

            using (SPWeb objSPWeb = itemTarget.Web)
            {
                foreach (SPField objSPField in itemTarget.Fields)
                {
                    try
                    {
                        strTag = string.Format("[{0}]", objSPField.Title);
                        if (strReturn.IndexOf(strTag, StringComparison.InvariantCultureIgnoreCase) < 0)
                            continue;

                        strValue = string.Empty;
                        if (objSPField.Type == SPFieldType.Lookup)
                        {
                            SPFieldLookupValue objLookupValue = (SPFieldLookupValue)itemTarget[objSPField.Title];
                            strValue = objLookupValue.LookupValue;
                        }
                        else if (objSPField.Type == SPFieldType.User)
                        {
                            SPFieldUserValue objUserValue = new SPFieldUserValue(objSPWeb, Convert.ToString(itemTarget[objSPField.Title]));
                            if (boolUserEmail)
                            {
                                strValue = objUserValue.User.Email;
                            }
                            else
                            {
                                strValue = objUserValue.User.Name;
                            }
                        }
                        else if (objSPField.Type == SPFieldType.URL)
                        {
                            SPFieldUrlValue objUrlValue = (SPFieldUrlValue)itemTarget[objSPField.Title];
                            strValue = string.Format(@"<a href='{0}'>{1}</a>", objUrlValue.Url, objUrlValue.Description);
                        }
                        else
                        {
                            strValue = Convert.ToString(itemTarget[objSPField.Title]);
                        }
                        strReturn = strReturn.Replace(strTag, strValue);
                    }
                    catch (Exception ex)
                    {
                        logTraceInfo(string.Format(@"ex, list title={0}, item id={1}, objSPField.Title={2}, strValue={3}, ItemId=", itemTarget.ParentList.Title, itemTarget.ID, objSPField.Title, strValue, iCfgItemId));
                        logTraceInfo(string.Format(@"ex.Message={0}", ex.Message));
                        logTraceInfo(string.Format(@"ex.StackTrace={0}", ex.StackTrace));

                        continue;
                    }
                }
            }

            return strReturn;
        }

        public static void SetToolbarTypeFreeForm(SPWeb objSPWeb, string strPageUrl, Guid guidStorageKey)
        {
            string storageKey = guidStorageKey.ToString("B").ToUpper();
            uint toolbarType = (uint)EFInspectUniquePerm.ListViewWebPartToolbarType.FreeForm;

            if (String.IsNullOrEmpty(storageKey) || storageKey == Guid.Empty.ToString())
                throw new Exception("The webpart must be added to the page before this method (SetToolbarType) can be called");

            SPLimitedWebPartManager limitedWebPartManager = null;
            limitedWebPartManager = objSPWeb.GetLimitedWebPartManager(strPageUrl, PersonalizationScope.Shared);

            ListViewWebPart lvwp = null;
            lvwp = (ListViewWebPart)limitedWebPartManager.WebParts[guidStorageKey];

            string listId = lvwp.ListName;
            string viewId = lvwp.ViewGuid;

            // get the SPWebPartManager from SPLimitedWebPartManager
            PropertyInfo webPartManagerProp = typeof(SPLimitedWebPartManager).GetProperty(
              "WebPartManager",
              BindingFlags.NonPublic | BindingFlags.Instance);
            SPWebPartManager webPartManager = (SPWebPartManager)webPartManagerProp.GetValue(limitedWebPartManager, null);

            // get the SPWebPartConnection from SPWebPartManager
            PropertyInfo spWebPartsProp = typeof(SPWebPartManager).GetProperty(
              "SPWebParts",
              BindingFlags.NonPublic | BindingFlags.Instance);
            SPWebPartCollection webParts = (SPWebPartCollection)spWebPartsProp.GetValue(webPartManager, null);

            // Call the ApplyViewToListWebPart method on the SPWebPartConnection
            // internal void ApplyViewToListWebPart(
            //    string storageKey,
            //    string listID,
            //    string viewID,
            //    uint toolbarType,
            //    out uint flags,
            //    out uint baseViewId)
            MethodInfo applyViewToListWebPart = typeof(SPWebPartCollection).GetMethod(
              "ApplyViewToListWebPart",
              BindingFlags.NonPublic | BindingFlags.Instance,
              null,
              new[]{
        typeof(string),
        typeof(string),
        typeof(string),
        typeof(uint),
        typeof(uint).MakeByRefType(),
        typeof(uint).MakeByRefType()
      },
              null);
            object[] parameters = new object[6];
            parameters[0] = storageKey;
            parameters[1] = listId;
            parameters[2] = viewId;
            parameters[3] = toolbarType;

            applyViewToListWebPart.Invoke(webParts, parameters);
        }

        public static void ShowToolbar(SPWeb objSPWeb, string strPageUrl, Guid guidStorageKey)
        {
            SPLimitedWebPartManager manager = null;
            manager = objSPWeb.GetLimitedWebPartManager(strPageUrl, PersonalizationScope.Shared);

            object[] setToolbarTypeParams = { (uint)EFInspectUniquePerm.ListViewWebPartToolbarType.ShowToolbar };
            ListViewWebPart objListViewWebPart = null;
            objListViewWebPart = (ListViewWebPart)manager.WebParts[guidStorageKey];

            PropertyInfo viewProp = objListViewWebPart.GetType().GetProperty("View", BindingFlags.Instance | BindingFlags.NonPublic);
            SPView webPartView = viewProp.GetValue(objListViewWebPart, null) as SPView;

            MethodInfo setToolbarType = webPartView.GetType().GetMethod("SetToolbarType",
                BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(uint) }, null);
            setToolbarType.Invoke(webPartView, setToolbarTypeParams);

            webPartView.Update();
            manager.SaveChanges(objListViewWebPart);
        }
        #endregion

    }
}
